package zhtt.controller;

import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.data.JRMapCollectionDataSource;
import net.sf.jasperreports.engine.export.HtmlExporter;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.export.SimpleExporterInput;
import net.sf.jasperreports.export.SimpleHtmlExporterOutput;
import net.sf.jasperreports.export.SimpleHtmlReportConfiguration;
import net.sf.jasperreports.j2ee.servlets.ImageServlet;
import net.sf.jasperreports.web.util.WebHtmlResourceHandler;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class JavabenController {

    private static final String REPORT_NAME = "reportName";
    private static final String FILE_FORMAT = "format";
    private static final String DATASOURCE = "datasource";

    /**
     * 直接使用模板文件中的sql语句得到报表
     *  http://127.0.0.1:8080/jasperreports02/user/itclj_report_A4?format=pdf
     * @param modelMap
     * @param reportName
     * @param format
     * @return
     */
    @RequestMapping("/{reportName}")
    public ModelAndView getReportByParam(final ModelMap modelMap,
                                         @PathVariable(REPORT_NAME) final String reportName,
                                         @RequestParam(FILE_FORMAT) final String format, HttpServletResponse response) {
        Collection itemsMap = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("name", "张山");
        map.put("student_id", "2017121108");
        map.put("ranking", 10);
        map.put("score_math", 97);
        map.put("score_chinese", 100);
        map.put("score_english", 78);
        map.put("score_chemistry", 70);
        map.put("score_physical", 89);
        map.put("score_biology", 99);
        map.put("score_top", 88);
        itemsMap.add(map);
        response.setContentType("text/html;charset=UTF-8");
        JRDataSource jrDataSource = new JRMapCollectionDataSource(itemsMap);
        modelMap.put(DATASOURCE, jrDataSource);
        modelMap.put(FILE_FORMAT, format);
        ModelAndView modelAndView = new ModelAndView(reportName, map);
        return modelAndView;
    }

    @RequestMapping("/report02")
    public ModelAndView report02(final ModelMap modelMap, @RequestParam(value = FILE_FORMAT,defaultValue = "pdf")  String format,HttpServletResponse response) {
        Collection itemsMap = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("title", "张山");
        map.put("author", "2017121108");
        map.put("date", 10);
        itemsMap.add(map);
        response.setContentType("text/html;charset=UTF-8");
        JRDataSource jrDataSource = new JRMapCollectionDataSource(itemsMap);
        modelMap.put(DATASOURCE, jrDataSource);
        modelMap.put(FILE_FORMAT, format);
        ModelAndView modelAndView = new ModelAndView("report2", map);
        return modelAndView;
    }

    @RequestMapping("/report04")
    public ModelAndView report04(final ModelMap modelMap, @RequestParam(value = FILE_FORMAT,defaultValue = "pdf")  String format, HttpServletResponse response) {
        Collection itemsMap = new ArrayList<>();
        Map<String, Object> map = getMap();
        itemsMap.add(map);
        response.setContentType("text/html;charset=UTF-8");
        JRDataSource jrDataSource = new JRMapCollectionDataSource(itemsMap);
        modelMap.put(DATASOURCE, jrDataSource);
        modelMap.put(FILE_FORMAT, format);
        ModelAndView modelAndView = new ModelAndView("report4", map);
        return modelAndView;
    }

    @RequestMapping("/report0401")
    public void report0401(final ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException {
        //1.获得报表模板文件。
        InputStream isRef = request.getServletContext().getResourceAsStream("/WEB-INF/classes/reports/report4.jasper");
        try {
            Collection itemsMap = new ArrayList<>();
            Map<String, Object> map = getMap();
            itemsMap.add(map);
            JasperReport jasperReport = (JasperReport) JRLoader.loadObject(isRef);
            //根据报表模板文件生成报表打印对象
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, map, new JRBeanCollectionDataSource(itemsMap));
            request.getSession().setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, jasperPrint);
            HtmlExporter exporterHTML = new HtmlExporter();
            SimpleExporterInput exporterInput = new SimpleExporterInput(jasperPrint);
            exporterHTML.setExporterInput(exporterInput);
            SimpleHtmlExporterOutput exporterOutput;
            exporterOutput = new SimpleHtmlExporterOutput(response.getOutputStream());
            exporterOutput.setImageHandler(new WebHtmlResourceHandler("image?image={0}"));
            exporterHTML.setExporterOutput(exporterOutput);
            SimpleHtmlReportConfiguration reportExportConfiguration = new SimpleHtmlReportConfiguration();
            reportExportConfiguration.setWhitePageBackground(false);
            reportExportConfiguration.setRemoveEmptySpaceBetweenRows(true);
            exporterHTML.setConfiguration(reportExportConfiguration);
            exporterHTML.exportReport();
        } catch (JRException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/report0402")
    public void report0402(final ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) throws IOException, JRException {
        //1.获得报表模板存放路径。
        String jasperFilePath = new StringBuilder("/WEB-INF/classes/reports/report4.jasper").toString();
        //2.获得报表模板文件
        //File reportFile = getWebApplicationContext(request).getResource(jasperFilePath).getFile();
        File reportFile = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext()).getResource(jasperFilePath).getFile();

        Collection itemsMap = new ArrayList<>();
        Map<String, Object> map = getMap();
        itemsMap.add(map);
        //3.根据报表模板文件生成报表打印对象
        //JasperPrint print = JasperFillManager.fillReport(reportFile.getAbsolutePath(), model, dataSource.getConnection());
        JRDataSource datesource = new JRBeanCollectionDataSource(itemsMap);
        JasperPrint print = JasperFillManager.fillReport(reportFile.getAbsolutePath(), map,datesource);
        //4.创建Html导出对象
        JRHtmlExporter exporter = new JRHtmlExporter();
        //5.设置图片文件存放路径，此路径为服务器上的绝对路径
        String imageDIR = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext()).getResource("reportFiles").getFile().getAbsolutePath();
        exporter.setParameter(JRHtmlExporterParameter.IMAGES_DIR_NAME, imageDIR);
        //6.设置图片请求URI
        String imageURI = request.getContextPath() + "/reportFiles/";
        exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, imageURI);
        //7.设置导出图片到图片存放路径
        exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.TRUE);
        exporter.setParameter(JRHtmlExporterParameter.IS_OUTPUT_IMAGES_TO_DIR, Boolean.TRUE);
        //8.设置导出对象
        exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
        //9.设置导出方法
        exporter.setParameter(JRExporterParameter.OUTPUT_WRITER, response.getWriter());
        exporter.setParameter(JRExporterParameter.CHARACTER_ENCODING, "utf-8"); //解决乱码问题
        //10.设置HTTP Head
        response.setContentType("text/html; charset=utf-8");
        //11.执行导出
        exporter.exportReport();
    }

    private Map getMap(){
        Map<String, Object> map = new HashMap<>();
        map.put("shi_shi_zhu_ti", "济南市公安局");
        map.put("ch_ban_ji_gou", "市公安局、区公安分局");
        map.put("gong_tong_shi_shi_bu_men", "无");
        map.put("fa_ding_shi_xian", "20 工作日");
        map.put("cheng_ruo_qi_xian", "7 工作日");
        map.put("zi_xun_dian_hua", "0531-85081562");
        map.put("tou_su_dian_hua", "0531-68966426");
        map.put("shi_fou_shou_fei", "否");
        map.put("shou_li_di_dian", "济南市市中区站前街9号 公安局窗口");
        map.put("shou_li_shi_jian", "周一至周五： 上午9:00-12:00 下午:13:00-17:30");
        return map;
    }
}
